using System;
using UnityEngine;

namespace IQIGame.Onigao.Framework
{
    public struct BVHBounds2D
    {
        public Vector2 min { get; private set; }
        public Vector2 max { get; private set; }

        public BVHBounds2D(Vector2 min, Vector2 max)
        {
            this.min = min;
            this.max = max;
        }

        public static BVHBounds2D FromRect(UnityEngine.Rect rect)
        {
            return new BVHBounds2D(rect.min, rect.max);
        }

        public static BVHBounds2D FromPosSize(Vector2 pos, Vector2 size)
        {
            Vector2 halfSize = size / 2;
            return new BVHBounds2D(pos - halfSize, pos + halfSize);
        }

        public static BVHBounds2D FromPosSize(Vector3 pos, Vector3 size)
        {
            Vector3 halfSize = size / 2;
            var min = pos - halfSize;
            var max = pos + halfSize;
            return new BVHBounds2D(new Vector2(min.x, min.z), new Vector2(max.x, max.z));
        }

        public static BVHBounds2D FromPosSizeRotationY(Vector2 pos, Vector2 size, float yRotation)
        {
            double rotation = yRotation * Math.PI / 180;
            Vector2 halfSize = size / 2;
            Vector2 axissX = new Vector2((float)Math.Cos(rotation), -(float)Math.Sin(rotation));
            Vector2 axissZ = new Vector2(-axissX.y, axissX.x);
            Vector2 axissXHalfSize = axissX * halfSize.x;
            Vector2 axissZHalfSize = axissZ * halfSize.y;
            Vector2 min = pos - axissXHalfSize - axissZHalfSize;
            Vector2 max = pos + axissXHalfSize + axissZHalfSize;
            return new BVHBounds2D(Vector2.Min(min, max), Vector2.Max(min, max));
        }

        public bool Intersects(BVHBounds2D other)
        {
            return !((max.x < other.min.x) || (min.x > other.max.x) ||
                   (max.y < other.min.y) || (min.y > other.max.y));
        }

        public bool Contains(Vector2 point)
        {
            return (point.x >= min.x) && (point.x <= max.x) &&
                   (point.y >= min.y) && (point.y <= max.y);
        }

        // 是否相等
        public bool IsEqual(BVHBounds2D other)
        {
            return min == other.min && max == other.max;
        }
    }
}